package logic

import (
	"context"

	"github.com/zeromicro/x/errors"

	GuitarModel "go-weixin/app/guitar/model"
	"go-weixin/app/guitar/rpc/internal/svc"
	"go-weixin/app/guitar/rpc/pb/proto/guitar"

	"github.com/zeromicro/go-zero/core/logx"
)

type GuitarAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGuitarAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GuitarAddLogic {
	return &GuitarAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GuitarAddLogic) GuitarAdd(in *guitar.GuitarAddReq) (*guitar.GuitarAddResp, error) {
	// mysql查询已注册
	has, err := l.svcCtx.ChenDb.Exist(&GuitarModel.GuitarModel{Title: in.Title})
	if err != nil {
		return nil, errors.New(8000, err.Error())
	}
	if has {
		return nil, errors.New(7000, "标题已存在")
	}
	// mysql插入
	accected, err := l.svcCtx.ChenDb.Insert(&GuitarModel.GuitarModel{Title: in.Title})
	if accected == 0 {
		return nil, errors.New(7000, "插入行数为0")
	}

	if err = l.svcCtx.KqClient.Push(in.Title); err != nil {
		return nil, errors.New(6000, "kq异常:"+err.Error())
	}

	return &guitar.GuitarAddResp{}, nil
}
